package initialize

import (
	"encoding/json"
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"rpc_demo/stock_srv/global"
)

func InitConfig() {

	v := viper.New()
	configFileName := "/Users/jinshijie/GolandProjects/shop_srv/stock_srv/config-debug.yaml"

	v.SetConfigFile(configFileName)
	if err := v.ReadInConfig(); err != nil {
		zap.S().Error("读取配置文件失败", err.Error())
		return
	}
	err := v.Unmarshal(global.NacosConfig)
	if err != nil {
		zap.S().Error("配置文件解析失败", err.Error())
		return
	}

	//动态监听变化
	v.WatchConfig()
	v.OnConfigChange(func(in fsnotify.Event) {
		if err := v.ReadInConfig(); err != nil {
			zap.S().Error("读取配置文件失败", err.Error())
			return
		}
		err := v.Unmarshal(&global.ServiceConfig)
		if err != nil {
			zap.S().Error("配置文件解析失败", err.Error())
			return
		}
	})

	//读取nocos 配置信息
	srvConfig := global.ServiceConfig
	serverConfigs := []constant.ServerConfig{
		{
			Scheme:      global.NacosConfig.Scheme,
			ContextPath: global.NacosConfig.ContextPath,
			IpAddr:      global.NacosConfig.IpAddress,
			Port:        global.NacosConfig.Port,
		},
	}

	clientConfig := constant.ClientConfig{

		NamespaceId:         global.NacosConfig.NamespaceId, // 如果需要支持多namespace，我们可以创建多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		TimeoutMs:           global.NacosConfig.TimeoutMs,
		NotLoadCacheAtStart: global.NacosConfig.NotLoadCacheAtStart,
		LogDir:              global.NacosConfig.LogDir,
		CacheDir:            global.NacosConfig.CacheDir,
		LogLevel:            global.NacosConfig.LogLevel,
	}

	configClient, _ := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})

	content, _ := configClient.GetConfig(vo.ConfigParam{
		DataId: global.NacosConfig.DataId,
		Group:  global.NacosConfig.Group,
	})

	err = json.Unmarshal([]byte(content), srvConfig)
	if err != nil {
		zap.S().Error("读取nacos配置信息失败", err.Error())
		return
	}
	
	err = configClient.ListenConfig(vo.ConfigParam{
		DataId: global.NacosConfig.DataId,
		Group:  global.NacosConfig.Group,
		OnChange: func(namespace, group, dataId, data string) {
			fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data)
		},
	})
}
